﻿using Newtonsoft.Json;
using WeShare.WeiXin.Applet.Login.Entity;
using WeShare.WeiXin.Common;
using WeShare.WeiXin.Common.EnumKey;

namespace WeShare.WeiXin.Applet.Login
{
    public class LoginApi
    {
        /// <summary>
        /// code换取session_key
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="secret"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public static CodeToSessionRes CodeToSession(string code,string appId="")
        {
            var apiconfig = OpenApi.GetConfig(appId, PlatformType.Mini);
            var url = $"https://api.weixin.qq.com/sns/jscode2session?appid={apiconfig.AppId}&secret={apiconfig.AppSecret}&js_code={code}&grant_type=authorization_code";
            return HttpUtil.GetResult<CodeToSessionRes>(url);
        }
        /// <summary>
        /// 根据密文，进行解密，获取用户信息
        /// </summary>
        /// <param name="encryptedData"></param>
        /// <param name="sessionKey"></param>
        /// <param name="iv"></param>
        /// <returns></returns>
        public static UserInfo GetUserInfo(string encryptedData, string sessionKey, string iv)
        {
            return JsonConvert.DeserializeObject<UserInfo>(Utils.Decrypt(encryptedData, sessionKey, iv));
        }
        /// <summary>
        /// 验证签名
        /// </summary>
        /// <param name="rawData"></param>
        /// <param name="sessionKey"></param>
        /// <param name="signature"></param>
        /// <returns></returns>
        public static bool ValidSign(string rawData, string sessionKey, string signature)
        {
            var sha1 = Utils.Sha1(rawData + sessionKey);
                
            if (sha1 != null)
            {
                var tempsign = sha1.ToLower();
                return signature == tempsign;
            }
            return false;
        }
    }
}
